import Vue from 'vue'
import axios from 'axios'
import { BASE_URL } from '../utils/url'
import { getToken, removeToken } from '../utils/token'
import router from '../router'

axios.defaults.baseURL = BASE_URL
axios.defaults.withCredentials = true

// 请求拦截器
axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    const token = getToken()
    if (token) {
      config.headers.token = token
    }
    return config
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  function(response) {
    if (response.data.code === 206) {
      // token无效或是过期了
      removeToken()

      router.push('/login')

      return null
    }
    return response
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error)
  }
)

Vue.prototype.$axios = axios
